package com.srwl.mytx.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.activity.CouponRecordActivity;
import com.srwl.mytx.R;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 一对一红包详情页面
 */
public class SingleCouponDetailFragment extends BaseFragment implements View.OnClickListener {
    private static final String TAG = SingleCouponDetailFragment.class.getSimpleName();

    private Coupon couponInfo;
    private String couponId;
    private TextView mTvMoneyStatus;
    private View receiverInfoLayout;
    private ProgressBar progressBar;
    private User targetUser;//对于红包接收者，这是红包发送者信息，对于红包发送者，这是红包接收者信息
    private ImageView mIvReceiverAvatar, mIvSenderAvatar;
    private TextView mTvReceiver;
    private TextView mTvItemAmount;
    private TextView mTvTime, mTvSender, mTvGreeting, mTvMoneyAmount, mTvMoneyUse, tvCheckRecords;
    private View statusLayout;
    private User myUser;
    private boolean isSender;// 红包发送者标记


    public static SingleCouponDetailFragment newInstance(Intent intent) {
        SingleCouponDetailFragment fragment = new SingleCouponDetailFragment();
        fragment.setArguments(intent.getExtras());
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rp_fragment_single_packet_detail, container, false);
        initViewsAndEvents(view);
        return view;

    }


    protected void initViewsAndEvents(View view) {
        if (getArguments() != null) {
            couponInfo = getArguments().getParcelable(Constant.EXTRA_INFO_COUPON);
            couponId = getArguments().getString("couponId");
            isSender = getArguments().getBoolean("isSender");
            if (couponInfo != null) {
                couponId = couponInfo.getId();
                targetUser = couponInfo.getTargetUser();
            }
        }

        myUser = UserProfileManager.getInstance().getLoginUserInfo();
        progressBar = view.findViewById(R.id.progress_bar);
        ImageView ivBg = view.findViewById(R.id.iv_detail_bg);
        mIvSenderAvatar = view.findViewById(R.id.iv_avatar);
        ImageView mIvIcon = view.findViewById(R.id.iv_group_random);
        mTvSender = view.findViewById(R.id.tv_money_sender);
        mTvGreeting = view.findViewById(R.id.tv_greeting);
        mTvMoneyAmount = view.findViewById(R.id.tv_money_amount);
        mTvMoneyUse = view.findViewById(R.id.tv_money_use);
        tvCheckRecords = view.findViewById(R.id.tv_check_records);
        mTvMoneyStatus = view.findViewById(R.id.tv_money_status);
        statusLayout = view.findViewById(R.id.status_layout);
        receiverInfoLayout = view.findViewById(R.id.layout_item);
        mIvReceiverAvatar = view.findViewById(R.id.iv_item_avatar_icon);
        mTvReceiver = view.findViewById(R.id.tv_money_to_user);
        mTvTime = view.findViewById(R.id.tv_time);
        mTvItemAmount = view.findViewById(R.id.tv_item_money_amount);
        tvCheckRecords.setOnClickListener(this);

        if (couponInfo != null) {
            isSender = TextUtils.equals(myUser.getuId(), couponInfo.getuId());
            if (isSender) { //红包发送方，去请求数据后，再展示，
                getCouponFromService(couponId);
            } else {//红包接收方
                if (targetUser == null) {//发送者信息为空时候，去获取远程数据后，再展示数据
                    getCouponFromService(couponId);
                } else {
                    showCoupon();
                }
            }
        } else { //红包信息是空的
            getCouponFromService(couponId);
        }
    }

    private void showCoupon() {

        mTvGreeting.setText(couponInfo.getGreeting());
        if (isSender) {  //红包发送者看到的红包详情内容
            showCouponSenderInfo(myUser);
            //发送方显示红包详情，依赖服务端返回的信息，在服务端返回信息之前，隐藏掉一些控件
            mTvMoneyStatus.setVisibility(View.VISIBLE);
            receiverInfoLayout.setVisibility(View.INVISIBLE);
            mTvMoneyAmount.setText(String.format(getString(R.string.detail_money_sign), couponInfo.getAmount().toString()));
            statusLayout.setVisibility(View.VISIBLE);
            mTvMoneyUse.setVisibility(View.GONE);
            tvCheckRecords.setVisibility(View.GONE);
            setView();

        } else {//红包接收者看到的红包详情内容
            showCouponSenderInfo(targetUser);
            statusLayout.setVisibility(View.GONE);
            receiverInfoLayout.setVisibility(View.GONE);
            mTvMoneyUse.setVisibility(View.VISIBLE);
            mTvMoneyAmount.setText(String.format(getString(R.string.detail_money_sign), couponInfo.getAmount().toString()));
            mTvMoneyUse.setText(getResources().getString(R.string.money_save_in_wallet));

        }
    }


    /**
     * 展示红包发送者信息
     *
     * @param couponSender
     */
    private void showCouponSenderInfo(User couponSender) {
        if (couponSender == null) return;
        mTvSender.setText(couponSender.getUsername());
        GlideLoadUtils.glideLoad(getActivity(), couponSender.getAvatar(), mIvSenderAvatar, R.drawable.tx_default_avatar_1);
    }

    /**
     * 根据id 去服务端获取红包信息
     */
    private void getCouponFromService(String couponId) {

        progressBar.setVisibility(View.VISIBLE);
        CouponService request = RetrofitManager.getInstance().createRequest(CouponService.class);
        Call<CommonResult> couponAndReceiverInfo = request.getCouponAndReceiverInfo(couponId);
        if (isSender) {
            couponAndReceiverInfo = request.getCouponAndReceiverInfo(couponId); //发送方获取 红包信息和接收者信息
        } else {
            couponAndReceiverInfo = request.getCouponAndSenderInfo(couponId); //接收方获取  红包信息和 发送者信息
        }
        couponAndReceiverInfo.enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                progressBar.setVisibility(View.GONE);
                CommonResult result = response.body();
                if (!response.isSuccessful() || result == null) {
                    Log.e(TAG, "获取优惠卷详情出错：" + response.message());
                    if (isAdded()) {
                        showToast(getResources().getString(R.string.system_busy));
                    }
                    return;
                }


                if (result.isError()) {
                    Log.e(TAG, "获取优惠卷详情出错：" + result.getMsg());
                    switch (result.getStatus()) {
                        case Constant.TOKEN_INVALID:
                            if (isAdded()) {
                                showToast(getResources().getString(R.string.login_expire));
                            }
                            break;
                    }

                    return;
                }
                //从服务端返回 优惠卷 详情
                Object data = result.getData();
                if (data != null) {
                    JSONObject object = (JSONObject) data;
                    Log.d(TAG, "获取优惠卷详情完成" + object.toString());
                    couponInfo = object.toJavaObject(Coupon.class);
                    isSender = TextUtils.equals(myUser.getuId(), couponInfo.getuId());
                    targetUser = couponInfo.getTargetUser();

                } else {//如果服务端找不到此条红包信息，一律当过期处理
                    couponInfo.setStatus(Constant.COUPON_STATUS_EXPIRED);
                }
                showCoupon();
            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                t.printStackTrace();
                if (isAdded()) {
                    showToast(getResources().getString(R.string.system_busy));
                }
            }
        });

    }

    private void setView() {
        if (couponInfo.getStatus() == Constant.COUPON_STATUS_RECEIVABLE) {
            receiverInfoLayout.setVisibility(View.GONE);

            if (couponInfo.getType() == Constant.COUPON_TYPE_ALI_FUND) {
                mTvMoneyStatus.setText(String.format(getResources().getString(R.string.fund_coupon_not_receive), couponInfo.getAmount().toString()));
            } else {
                mTvMoneyStatus.setText(String.format(getResources().getString(R.string.coin_coupon_not_receive), couponInfo.getAmount().toString()));
            }
        } else if (couponInfo.getStatus() == Constant.COUPON_STATUS_RECEIVED) {
            //显示接收方信息
            receiverInfoLayout.setVisibility(View.VISIBLE);
            if (targetUser != null) {
                GlideLoadUtils.glideLoad(getActivity(), targetUser.getAvatar(), mIvReceiverAvatar, R.drawable.tx_default_avatar_1);
                mTvReceiver.setText(targetUser.getUsername());
            }
            if (couponInfo.getUpdated() != null) {
                mTvTime.setText(DateUtils.getTimestampString(couponInfo.getUpdated()));
            } else {
                mTvTime.setText(DateUtils.getTimestampString(couponInfo.getCreated()));
            }
            mTvItemAmount.setText(String.format(getString(R.string.detail_money_sign), Utils.moneyFormat(couponInfo.getAmount())));
            if (couponInfo.getType() == Constant.COUPON_TYPE_ALI_FUND) {
                mTvMoneyStatus.setText(String.format(getResources().getString(R.string.fund_coupon_received), couponInfo.getAmount().toString()));
            } else {
                mTvMoneyStatus.setText(String.format(getResources().getString(R.string.coin_coupon_received), couponInfo.getAmount().toString()));
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_check_records) {
            //跳转到红包记录页面
            Intent intent = new Intent(getActivity(), CouponRecordActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }


}
